import { createRouter, createWebHistory } from 'vue-router'
import MainLayout from '@/layouts/MainLayout.vue'
import { Permission, Role, hasPermission, hasRole } from '@/utils/permission'
import { isLoggedIn, initUserState, fetchUserInfo } from '@/utils/userStore'
import { ElMessage } from 'element-plus'

const router = createRouter({
  history: createWebHistory(),
  routes: [
    {
      path: '/',
      redirect: '/login'
    },
    {
      path: '/login',
      name: 'Login',
      component: () => import('@/views/login/index.vue'),
      meta: {
        title: '登录',
        requiresAuth: false
      }
    },
    {
      path: '/register',
      name: 'Register',
      component: () => import('@/views/register/index.vue'),
      meta: {
        title: '注册',
        requiresAuth: false
      }
    },
    {
      path: '/',
      component: MainLayout,
      children: [
        {
          path: 'dashboard',
          name: 'Dashboard',
          component: () => import('@/views/dashboard/index.vue'),
          meta: { 
            title: '仪表盘',
            requiresAuth: true,
            icon: 'Monitor',
            permissions: [] // 所有角色都可访问
          }
        },
        {
          path: 'customers',
          name: 'Customers',
          component: () => import('@/views/customers/index.vue'),
          meta: {
            title: '客户管理',
            requiresAuth: true
          },
          children: [
            {
              path: 'list',
              name: 'CustomerList',
              component: () => import('@/views/customers/MyAssistedCustomers.vue'),
              meta: {
                title: '我协助的客户',
                requiresAuth: true
              }
            },
            {
              path: 'mine',
              name: 'MyCustomers',
              component: () => import('@/views/customers/MyFollowupCustomers.vue'),
              meta: {
                title: '我跟进的客户',
                requiresAuth: true
              }
            },
            {
              path: 'groups',
              name: 'CustomerGroups',
              component: () => import('@/views/customers/AppointmentCustomers.vue'),
              meta: {
                title: '预约上门客户',
                requiresAuth: true
              }
            },
            {
              path: 'public-sea',
              name: 'PublicSeaCustomers',
              component: () => import('@/views/customers/PublicSeaCustomers.vue'),
              meta: {
                title: '公海客户',
                requiresAuth: true
              }
            },
            {
              path: 'effective-leads',
              name: 'EffectiveLeads',
              component: () => import('@/views/customers/EffectiveLeads.vue'),
              meta: {
                title: '有效线索',
                requiresAuth: true
              }
            },
            {
              path: 'resource-pool',
              name: 'CustomerResourcePool',
              component: () => import('@/views/customers/ResourcePool.vue'),
              meta: {
                title: '资源库',
                requiresAuth: true
              }
            },
            {
              path: 'round-robin-tasks',
              name: 'RoundRobinTasks',
              component: () => import('@/views/customers/RoundRobinTasks.vue'),
              meta: {
                title: '轮呼任务',
                requiresAuth: true
              },
              children: [
                {
                  path: ':id',
                  name: 'RoundRobinTaskDetail',
                  component: () => import('@/views/customers/RoundRobinTaskDetail.vue'),
                  meta: {
                    title: '轮呼任务详情',
                    requiresAuth: true
                  }
                }
              ]
            }
          ]
        },
        {
          path: 'platforms',
          name: 'Platforms',
          component: () => import('@/views/platforms/index.vue'),
          meta: { 
            title: '平台适配器',
            requiresAuth: true,
            icon: 'Link',
            permissions: [Permission.VIEW_PLATFORMS]
          }
        },
        {
          path: 'monitor',
          name: 'Monitor',
          component: () => import('@/views/monitor/index.vue'),
          meta: { 
            title: '消息监控',
            requiresAuth: true,
            icon: 'Bell',
            permissions: [Permission.VIEW_MONITOR]
          }
        },
        {
          path: 'user',
          name: 'User',
          component: () => import('@/views/user/index.vue'),
          meta: { 
            title: '用户',
            requiresAuth: true,
            icon: 'User',
            permissions: [Permission.VIEW_USERS],
            roles: [Role.ADMIN, Role.SUPER_ADMIN] // 只有管理员和超级管理员可访问
          }
        },
        {
          path: 'message',
          name: 'Message',
          component: () => import('@/views/message/index.vue'),
          meta: { 
            title: '消息',
            requiresAuth: true,
            icon: 'Message',
            permissions: [Permission.VIEW_MESSAGES]
          }
        },
        {
          path: 'friend-tags',
          name: 'FriendTags',
          component: () => import('@/views/friend-tags/index.vue'),
          meta: { 
            title: '好友管理',
            requiresAuth: true,
            icon: 'UserFilled',
            permissions: [Permission.VIEW_FRIEND_TAGS]
          }
        },
        {
          path: 'material-library',
          name: 'MaterialLibrary',
          component: () => import('@/views/material-library/index.vue'),
          meta: {
            title: '素材库',
            requiresAuth: true,
            icon: 'Document',
            permissions: [Permission.VIEW_MATERIAL_LIBRARY]
          }
        },
        {
          path: 'official-contacts',
          name: 'OfficialContacts',
          component: () => import('@/views/official-contacts/OfficialContactList.vue'),
          meta: {
            title: '官网联系人',
            requiresAuth: true,
            icon: 'UserFilled',
            permissions: [] // 所有角色都可访问
          }
        },
        {
          path: 'settings',
          name: 'Settings',
          component: () => import('@/views/settings/index.vue'),
          meta: {
            title: '设置',
            requiresAuth: true,
            icon: 'Setting',
            permissions: [Permission.VIEW_SETTINGS],
            roles: [Role.ADMIN, Role.SUPER_ADMIN] // 只有管理员和超级管理员可访问
          }
        }
      ]
    },
    // 404页面
    {
      path: '/:pathMatch(.*)*',
      name: 'NotFound',
      component: () => import('@/views/404.vue'),
      meta: {
        title: '页面不存在',
        requiresAuth: false
      }
    }
  ]
})

// 初始化用户状态
initUserState()

// 路由守卫
router.beforeEach(async (to, from, next) => {
  // const token = localStorage.getItem('token')
  // 检查是否需要认证
  // if (to.meta.requiresAuth) {
  //   if (!token) {
  //     ElMessage.warning('请先登录')
  //     next({ path: '/login', query: { redirect: to.fullPath } })
  //     return
  //   }
  // // 如果有token但没有用户信息，尝试获取用户信息
  //   if (token && !isLoggedIn.value) {
  //     const success = await fetchUserInfo()
  //     if (!success) {
  //       ElMessage.warning('请先登录')
  //       next({ path: '/login', query: { redirect: to.fullPath } })
  //       return
  //     }
  //   }
  // }
  // 检查是否需要认证
  if (to.meta.requiresAuth) {
    const token = localStorage.getItem('token')
    
    // 如果没有token，直接跳转到登录页
    if (!token) {
      ElMessage.warning('请先登录')
      next({ path: '/login', query: { redirect: to.fullPath } })
      return
    }
    
    // 如果有token但没有用户信息，尝试获取用户信息
    if (token && !isLoggedIn.value) {
      const success = await fetchUserInfo()
      if (!success) {
        ElMessage.warning('登录已失效，请重新登录')
        next({ path: '/login', query: { redirect: to.fullPath } })
        return
      }
    }
  }
  
  // 如果已登录且访问登录页，则重定向到仪表盘
  if (isLoggedIn.value && (to.path === '/login' || to.path === '/register')) {
    next({ path: '/dashboard' })
    return
  }
  
  // 检查权限
  if (to.meta.permissions && Array.isArray(to.meta.permissions) && to.meta.permissions.length > 0) {
    const hasRequiredPermission = (to.meta.permissions as Permission[]).some(permission => 
      hasPermission(permission)
    )
    
    if (!hasRequiredPermission) {
      ElMessage.error('您没有访问该页面的权限')
      next({ path: '/dashboard' })
      return
    }
  }
  
  // 检查角色
  if (to.meta.roles && Array.isArray(to.meta.roles) && to.meta.roles.length > 0) {
    const hasRequiredRole = (to.meta.roles as Role[]).some(role => 
      hasRole(role)
    )
    
    if (!hasRequiredRole) {
      ElMessage.error('您的角色无法访问该页面')
      next({ path: '/dashboard' })
      return
    }
  }
  
  // 设置页面标题
  if (to.meta.title) {
    document.title = `${to.meta.title} - 微信管理系统`
  }
  
  next()
})

export default router